package com.kingtone.rongji;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.TreeSet;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.trinea.android.view.autoscrollviewpager.AutoScrollViewPager;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.kingtone.rongji.adapter.ProductImageAdapter;
import com.kingtone.rongji.biz.CommonMessage;
import com.kingtone.rongji.biz.HomeImage;
import com.kingtone.rongji.biz.Product;
import com.kingtone.rongji.biz.ProductDetail;
import com.kingtone.rongji.biz.ProductGroup;
import com.kingtone.rongji.biz.ProductImageSet;
import com.kingtone.rongji.biz.ProductProperty;
import com.kingtone.rongji.network.ProductDetailRequest;
import com.kingtone.rongji.tool.AppContasts;
import com.kingtone.rongji.tool.AppRestClient;
import com.kingtone.rongji.tool.CartUtils;
import com.kingtone.rongji.tool.DensityUtil;
import com.kingtone.rongji.tool.ListUtils;
import com.kingtone.rongji.tool.RongJiUtils;
import com.kingtone.rongji.tool.SharedPreferencesUtil;
import com.kingtone.rongji.ui.BadgeView;
import com.kingtone.rongji.ui.ProgressWebView;
import com.kingtone.rongji.ui.ToastManager;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageSize;

public class ProductDetailActivity extends BaseActivity implements
		OnClickListener {

	private static final String TAG = "ProductDetailActivity";

	private Activity mContext;

	private AutoScrollViewPager viewPager;
	private LinearLayout dotsView;
	private List<HomeImage> imageList;
	private List<ImageView> dotsItemView;

	private TextView title;
	private TextView lineDescription;
	private TextView price;
	private ImageView rate;
	private LinearLayout group;
	private ImageView plus;
	private ImageView minus;
	private EditText count;
	private Button addToCart;
	private Button otherCondition;
	private View cartImage;
	private ImageView fav;
	private ImageView share;

	private BadgeView badge;
	private int totalCounts;

	private ProgressWebView mWebView;

	private PullToRefreshScrollView mScrollView;
	private LinearLayout mLoading;
	private RadioGroup outerContentTabs;

	private FrameLayout myShopCart;
	
	private String productId;
	private ProductImageAdapter imageAdapter;

	private ProductDetail detail;

	private String userId;
	private boolean isFavorited;

	@Override
	protected void onCreate(Bundle paramBundle) {
		super.onCreate(paramBundle);
		this.mContext = this;
		this.setContentView(R.layout.activity_detail);

		productId = getIntent().getExtras().getString("productId");

		SharedPreferencesUtil shared = SharedPreferencesUtil
				.getInstance(mContext);
		userId = shared.getString(AppContasts.USERID_KEY);

		initData();

		createViewPager();

		initProductDetail();

		creatWebView();

		final LinearLayout mainContainer  = (LinearLayout) this.findViewById(R.id.mainContainer);
		mScrollView = (PullToRefreshScrollView) this.findViewById(R.id.pull_refresh_scroll);
		//mScrollView.setDisableLoading(true);
		mScrollView.setOnRefreshListener(new OnRefreshListener2<ScrollView>(){  
			@Override
			public void onPullDownToRefresh(
					PullToRefreshBase<ScrollView> refreshView) {
				// TODO Auto-generated method stub
				mainContainer.setVisibility(View.VISIBLE);
				outerContentTabs.setVisibility(View.GONE);
				resetDetailTab();
				mWebView.setVisibility(View.GONE);
		    	mScrollView.onRefreshComplete();
		    	mScrollView.setMode(Mode.PULL_UP_TO_REFRESH);
			}

			@Override
			public void onPullUpToRefresh(
					PullToRefreshBase<ScrollView> refreshView) {
				// TODO Auto-generated method stub
				mainContainer.setVisibility(View.GONE);
				outerContentTabs.setVisibility(View.VISIBLE);
				mWebView.setVisibility(View.VISIBLE);
				mWebView.loadUrl(AppRestClient.BASE_PRODUCT_DESCRIPTION_URL+ productId);
				//mWebView.loadUrl("file:///android_asset/www/index.html");
		    	mScrollView.onRefreshComplete();
		    	mScrollView.setMode(Mode.PULL_DOWN_TO_REFRESH);
			}  
        });  
		
		outerContentTabs.setOnCheckedChangeListener(new OnCheckedChangeListener() {
				@Override
				public void onCheckedChanged(RadioGroup group, int id) {
					// TODO Auto-generated method stub
					if (id == R.id.outer_content) {
						mWebView.loadUrl("javascript:changeDetailTable(this, event, 1)");
					}
					if (id == R.id.outer_property) {
						mWebView.loadUrl("javascript:changeDetailTable(this, event, 2)");
					}
					if (id == R.id.outer_comments) {
						mWebView.loadUrl("javascript:changeDetailTable(this, event, 3)");
					}
					
					new Handler().postDelayed(new Runnable() {
					    @Override
					    public void run() {
					    	mScrollView.getRefreshableView().fullScroll(ScrollView.FOCUS_UP);
					    }
					}, 100);
				}
		});
		
		myShopCart = (FrameLayout) this.findViewById(R.id.shopcartImage);
		myShopCart.setOnClickListener(this);
	}

	private void initProductDetail() {
		// TODO Auto-generated method stub
		title = (TextView) this.findViewById(R.id.product_name);
		lineDescription = (TextView) this
				.findViewById(R.id.product_description);
		price = (TextView) this.findViewById(R.id.product_price);
		rate = (ImageView) this.findViewById(R.id.product_rate);

		group = (LinearLayout) this.findViewById(R.id.group_container);
		addToCart = (Button) this.findViewById(R.id.add_cart);
		otherCondition = (Button) this.findViewById(R.id.other_condition);

		plus = (ImageView) this.findViewById(R.id.img_plus);
		minus = (ImageView) this.findViewById(R.id.img_minus);
		count = (EditText) this.findViewById(R.id.et_count);
		View cartImage = this.findViewById(R.id.shopcartImage);
		badge = new BadgeView(this, cartImage);
		totalCounts = CartUtils.getCartCounts(mContext);
		if (totalCounts > 0) {
			badge.setText("" + totalCounts);
			badge.show();
		} else {
			badge.hide();
		}

		ImageView backBtn = (ImageView) this.findViewById(R.id.back);
		backBtn.setOnClickListener(this);
		fav = (ImageView) this.findViewById(R.id.id_img_fav);
		fav.setOnClickListener(this);
		share = (ImageView) this.findViewById(R.id.id_img_share);
		share.setOnClickListener(this);
	}

	private void initData() {
		// TODO Auto-generated method stub
		ProductDetailRequest detailRequest = new ProductDetailRequest();
		// productId = "10210002004";
		detailRequest.findDetail(productId, this);
		detailRequest.findGallery(productId, this);
		if (userId != null && userId.trim().length() > 0) {
			isFavorited = false;
			detailRequest.checkFavorite(productId, userId, this);
		}
		detailRequest.findDetailGroup(productId, this);
	}

	private void creatWebView() {
		mLoading = (LinearLayout) this.findViewById(R.id.id_loading);
		outerContentTabs = (RadioGroup) this.findViewById(R.id.outer_content_tabs);
		mWebView = (ProgressWebView) this.findViewById(R.id.id_wv_detail);
		mWebView.setWebViewClient(new WebViewClient() {
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				view.loadUrl(url);
				return true;
			}
		});
		mWebView.addJavascriptInterface(this, "productDetail");
	}
	
	@JavascriptInterface
	public void changeDetailTable(final String indexStr) {
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				if(indexStr != null && indexStr.trim().length() > 0)
				{
					int index = Integer.parseInt(indexStr);
					RadioButton button = (RadioButton) outerContentTabs.getChildAt(--index);
					button.setChecked(true);
				}
			}
		});
	}
	
	public void resetDetailTab()
	{
		if(outerContentTabs != null)
		{
			RadioButton button = (RadioButton) outerContentTabs.getChildAt(0);
			if(button != null)
			{
				button.setChecked(true);
			}
		}
	}

	private void createViewPager() {
		viewPager = (AutoScrollViewPager) this.findViewById(R.id.id_vp_product);
		LayoutParams lp = viewPager.getLayoutParams();
		lp.height = this.getWindowManager().getDefaultDisplay().getWidth();
		viewPager.setLayoutParams(lp);
		dotsView = (LinearLayout) this.findViewById(R.id.dots);

		imageList = new ArrayList<HomeImage>();
		dotsItemView = new ArrayList<ImageView>();
		
		viewPager.setOnPageChangeListener(new MyOnPageChangeListener());
        viewPager.setAutoScrollDurationFactor(8.0);
		viewPager.startAutoScroll();
	}

	private void setCurrentDotItem(int index) {
		if (null == dotsItemView) {
			return;
		}
		if (index > -1 && index < dotsItemView.size()) {
			for (int i = 0; i < dotsItemView.size(); i++) {
				if (index == i) {
					dotsItemView.get(i)
							.setImageResource(R.drawable.dot_pressed);
				} else {
					dotsItemView.get(i).setImageResource(R.drawable.dot);
				}
			}
		}
	}

	public class MyOnPageChangeListener implements OnPageChangeListener {
		@Override
		public void onPageSelected(int position) {
			int size = ListUtils.getSize(imageList);
			setCurrentDotItem((position) % (size == 0 ? 1 : size));
		}

		@Override
		public void onPageScrolled(int position, float positionOffset,
				int positionOffsetPixels) {
		}

		@Override
		public void onPageScrollStateChanged(int arg0) {
		}
	}

	@Override
	public void onResume() {
		super.onResume();
		viewPager.startAutoScroll();
		updateBadge(0, false);
	}

	@Override
	public void onPause() {
		super.onPause();
		viewPager.stopAutoScroll();
	}

	public void updateBadge(int count, boolean isAdd)
	{
		List<Product> datas = CartUtils.getAllProductsForCart(this);
		int c = 0;
		for(Product item:datas) {
			c+=item.getQuantity();
		}
		this.totalCounts = c;
		
		View empty = myShopCart.findViewById(R.id.shop_cart_empty);
		View full = myShopCart.findViewById(R.id.shop_cart_full);
		if(this.totalCounts > 0)
		{
			badge.setText("" + totalCounts);
			badge.show();
			empty.setVisibility(View.INVISIBLE);
			full.setVisibility(View.VISIBLE);
		}
		else
		{
			badge.hide();
			empty.setVisibility(View.VISIBLE);
			full.setVisibility(View.INVISIBLE);
		}
	}
	
	@Override
	public void onClick(View view) {
		// TODO Auto-generated method stub
		int id = view.getId();
		switch (id) {
		case R.id.shopcartImage:
			Intent intent = new Intent(ProductDetailActivity.this,
					CartActivity.class);
			startActivity(intent);
			break;
		case R.id.back:
			mContext.onBackPressed();
			break;
		case R.id.id_img_fav:
			if (userId != null && userId.trim().length() > 0) {
				if (isFavorited) {
					ToastManager.show(
							this,
							this.getResources().getString(
									R.string.add_fav_failed));
				} else {
					ProductDetailRequest pdReqeust = new ProductDetailRequest();
					pdReqeust.addFavorites(productId, userId,
							detail.getUnitPrice(), this);
				}
			} else {
				Intent login = new Intent(this, LoginActivity.class);
				login.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				login.putExtra("fromProductDetail", true);
				login.putExtra("productId", this.productId);
				startActivity(login);
			}
			break;
		case R.id.id_img_share:
			share();
			break;
		default:
			break;
		}
	}

	private void share() {
		OnekeyShare oks = new OnekeyShare();
		oks.disableSSOWhenAuthorize();
		String productUrl = AppRestClient.PRODUCT_DETAIL_URL + detail.getProductId();
		//oks.setTitle(detail.getProductName());
		//oks.setTitleUrl(productUrl);
		oks.setUrl(productUrl);
		String imageUrl = AppRestClient.convertImageUrl(detail.getProductId(), detail.getImageName());
		oks.setImagePath(convertImagePath(imageUrl));
		oks.setText(this.mContext.getResources().getString(R.string.share_product, new String[]{detail.getTitle(), productUrl}));
		oks.setSite(mContext.getString(R.string.app_name));
		oks.setSiteUrl(AppRestClient.WEBSITE_URL);
		oks.show(mContext);
	}

	public String convertImagePath(String imageUrl)
	{
		ImageSize imageSize = new ImageSize(100, 100);
		Bitmap bitmap = ImageLoader.getInstance().loadImageSync(imageUrl, imageSize);
		return RongJiUtils.storeInSD(bitmap, detail.getImageName());
	}
	@SuppressWarnings("unchecked")
	@Override
	public void onBussinessSuccess(Object obj) {
		super.onBussinessSuccess(obj);
		if (obj instanceof ProductImageSet) {
			ProductImageSet imageSet = (ProductImageSet) obj;
			String imageNames = imageSet.getFullImageName();
			String[] images = imageNames.split(",");
			HomeImage item = null;
			ImageView itemDot = null;
			String imageUrl = null;
			for (String imageName : images) {
				item = new HomeImage();
				imageUrl = AppRestClient.convertImageUrl(
						imageSet.getProductId(), imageName);
				item.setImageUrl(imageUrl);
				item.setAdvImageId(imageName);
				imageList.add(item);

				itemDot = new ImageView(this);
				itemDot.setImageResource(R.drawable.dot);
				dotsItemView.add(itemDot);
				dotsView.addView(itemDot);
			}
			imageAdapter = new ProductImageAdapter(this, imageList).setInfiniteLoop(true);
			viewPager.setAdapter(imageAdapter);
			viewPager.setCurrentItem(0);
			setCurrentDotItem(0);
			
		} else if (obj instanceof ArrayList) {
			List<ProductGroup> groups = (List<ProductGroup>) obj;
			Hashtable<String, TreeSet<ProductProperty>> results = new Hashtable<String, TreeSet<ProductProperty>>();
			for (ProductGroup group : groups) {
				String propertyName = group.getPropertyName();
				String productId2 = group.getProductId().trim();
				String propertyValue = group.getProductUserInputOrValue();
				if (productId2 != null && (propertyValue != null)) {
					ProductProperty property = new ProductProperty(productId2,
							propertyValue);
					if(productId2.equals(productId))
					{
						if (!results.containsKey(propertyName)) {
							results.put(propertyName,
									new TreeSet<ProductProperty>());
						}
						results.get(propertyName).add(property);
					}
				}
			}
			for (ProductGroup group : groups) {
				String propertyName = group.getPropertyName();
				String productId = group.getProductId().trim();
				String propertyValue = group.getProductUserInputOrValue();
				if (productId != null && (propertyValue != null)) {
					ProductProperty property = new ProductProperty(productId,
							propertyValue);
					if (!results.containsKey(propertyName)) {
						results.put(propertyName,
								new TreeSet<ProductProperty>());
					}
					results.get(propertyName).add(property);
				}
			}

			Iterator<String> iterator = results.keySet().iterator();
			while (iterator.hasNext()) {
				LinearLayout layout = new LinearLayout(this);
				layout.setLayoutParams(new LinearLayout.LayoutParams(
						LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
				layout.setOrientation(LinearLayout.HORIZONTAL);

				String key = iterator.next();
				TextView nameTV = new TextView(this);
				int padding = DensityUtil.dip2px(mContext, 10);
				int width = DensityUtil.dip2px(mContext, 50);
				nameTV.setPadding(0, padding, 0, padding);
				nameTV.setMinimumWidth(width);
				nameTV.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
				nameTV.setText(key + ":");
				layout.addView(nameTV);
				
				TreeSet<ProductProperty> keySet = results.get(key);
				
				for (ProductProperty property : keySet) {
					final String productId = property.getPoductId();
					TextView proTV = new TextView(this);
					int padding2 = DensityUtil.dip2px(mContext, 5);
					proTV.setPadding(padding2, padding2, padding2, padding2);
					String value = property.getProductUserInputOrValue();
					proTV.setText((value == null || value.trim().length() == 0) ? property
							.getUserInput() : value);
					if (productId.equals(this.productId)) {
						proTV.setBackgroundResource(R.drawable.bg_product_group_selected);
					} else {
						proTV.setBackgroundResource(R.drawable.bg_product_group_normal);
					}
					proTV.setOnClickListener(new View.OnClickListener() {
						@Override
						public void onClick(View v) {
							Intent intent = new Intent(mContext,
									ProductDetailActivity.class);
							Bundle ext = new Bundle();
							ext.putString("productId", productId);
							intent.putExtras(ext);
							mContext.startActivity(intent);
						}
					});
					layout.addView(proTV);

					View margin = new View(this);
					LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
							LinearLayout.LayoutParams.WRAP_CONTENT,
							LinearLayout.LayoutParams.WRAP_CONTENT);
					lp.width = padding;
					margin.setLayoutParams(lp);
					layout.addView(margin);
				}

				View line = new View(this);
				line.setBackgroundResource(R.drawable.dotted_line);

				group.addView(line);
				group.addView(layout);
			}
		} else if (obj instanceof ProductDetail) {
			detail = (ProductDetail) obj;
			title.setText(detail.getTitle());
			String description = detail.getLineDescription();
			if (description != null && description.trim().length() > 0) {
				lineDescription.setText(description);
				lineDescription.setVisibility(View.VISIBLE);
			} else {
				lineDescription.setVisibility(View.GONE);
			}

			if (detail.getTotalInventory() > 0) {//库存数量
				
				if(!detail.getActive()) //商品下架
				{
					this.plus.setOnClickListener(null);
					this.minus.setOnClickListener(null);
					this.count.setEnabled(false);
					addToCart.setVisibility(View.GONE);
					otherCondition.setVisibility(View.VISIBLE);
					otherCondition.setText(this.getResources().getString(
							R.string.product_deactive));
				}
				else
				{
					otherCondition.setVisibility(View.GONE);
					addToCart.setVisibility(View.VISIBLE);
					count.setEnabled(true);
					plus.setOnClickListener(new View.OnClickListener() {
	
						@Override
						public void onClick(View view) {
							// TODO Auto-generated method stub
							int tempCount = 0;
							String value = count.getText().toString();
							if (value != null && value.trim().length() > 0) {
								tempCount = Integer.parseInt(value);
							}
							String size = String.valueOf(++tempCount);
							count.setText(size);
							totalCounts++;
							updateCartBage(totalCounts);
						}
					});
					minus.setOnClickListener(new View.OnClickListener() {
	
						@Override
						public void onClick(View arg0) {
							// TODO Auto-generated method stub
							int tempCount = 1;
							String value = count.getText().toString();
							if (value != null && value.trim().length() > 0) {
								tempCount = Integer.parseInt(value);
							}
							if (tempCount > 1) {
								String size = String.valueOf(--tempCount);
								count.setText(size);
								totalCounts--;
								updateCartBage(totalCounts);
							}
						}
					});
	
					addToCart.setOnClickListener(new View.OnClickListener() {
						@Override
						public void onClick(View current) {
							Context context = current.getContext();
							String value = count.getText().toString();
							if (value != null && value.trim().length() >= 0) {
								int countInt = Integer.parseInt(value);
								if (countInt > detail.getActualInventory()) {
									ToastManager.show(
											context,
											current.getResources().getString(
													R.string.add_to_cart_no_inv));
									return;
								}
								if (countInt > detail.getLimitQuantity()) {
									ToastManager.show(
											context,
											current.getResources().getString(
													R.string.add_to_cart_limit));
									return;
								}
	
								CartUtils.add2Cart(
										context,
										new Product(detail.getProductId(), detail.getTitle(),
												detail.getProductName(), detail
														.getImageName(), detail
														.getUnitPrice(),
												countInt));
								ToastManager.show(context, current.getResources()
										.getString(R.string.add_to_cart_success));
	
								count.setText("" + countInt);
	
								totalCounts += countInt;
								updateCartBage(totalCounts);
	
								return;
							}
							ToastManager.show(context, current.getResources()
									.getString(R.string.add_to_cart_error));
						}
					});
				}
			} else {
				this.plus.setOnClickListener(null);
				this.minus.setOnClickListener(null);
				this.count.setEnabled(false);
				addToCart.setVisibility(View.GONE);
				otherCondition.setVisibility(View.VISIBLE);
				otherCondition.setText(this.getResources().getString(
						R.string.product_no_Inventory));
			}

			price.setText(this.getResources().getString(R.string.price_prefix)
					+ detail.getUnitPrice());
			
			int countLevel = this.detail.getReviewCountLevel();
			switch(countLevel)
			{
				case 1:
					rate.setImageResource(R.drawable.one_star);
					break;
				case 2:
					rate.setImageResource(R.drawable.two_star);
					break;
				case 3:
					rate.setImageResource(R.drawable.three_star);
					break;
				case 4:
					rate.setImageResource(R.drawable.four_star);
					break;
				case 5:
					rate.setImageResource(R.drawable.five_star);
					break;
				default:
					rate.setImageResource(R.drawable.star);
					break;
			}
			
		} else if (obj instanceof CommonMessage) {
			fav.setImageResource(R.drawable.ic_action_favorited);
			this.isFavorited = true;
		}

	}

	private void updateCartBage(int count) {
		View empty = myShopCart.findViewById(R.id.shop_cart_empty);
		View full = myShopCart.findViewById(R.id.shop_cart_full);
		if(count > 0)
		{
			badge.setText("" + totalCounts);
			badge.show();
			empty.setVisibility(View.INVISIBLE);
			full.setVisibility(View.VISIBLE);
		}
		else
		{
			badge.hide();
			empty.setVisibility(View.VISIBLE);
			full.setVisibility(View.INVISIBLE);
		}
	}
	
	@Override
	public void onBussinessSuccessWithToast(CommonMessage common) {
		// TODO Auto-generated method stub
		ToastManager.show(mContext,
				this.getResources().getString(R.string.add_fav_success));
	}
}
